package com.tcs.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.tcs.model.Article;

@Repository("articleDao")
public class ArticleDaoImpl implements ArticleDao {

	@Autowired
	private SessionFactory sessionFactory;

	public void saveArticle(Article article) {
		sessionFactory.getCurrentSession().saveOrUpdate(article);
	}

	@Transactional
	public void updateArticle(Article article) {
		sessionFactory.getCurrentSession().update(article);
	}

	@Transactional
	public void deleteArticle(int id) {
		sessionFactory.getCurrentSession().delete(this.getArticle(id));
	}

	@Transactional
	public void deleteListOfArticle(int brandId) {
		List<Article> listArticle = this.listArticlesByBrand(brandId);
		for (int i = 0; i < listArticle.size(); i++) {

			sessionFactory.getCurrentSession().delete(listArticle.get(i));

		}

	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Article> listArticles() {
		return (List<Article>) sessionFactory.getCurrentSession()
				.createCriteria(Article.class).list();
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly = true)
	public List<Article> listArticlesByBrand(int ID) {
		List<Article> list = (List<Article>) sessionFactory.getCurrentSession()
				.createCriteria(Article.class).list();
		List<Article> subList = new ArrayList<Article>();
		for (int i = 0; i < list.size(); i++) {
			if ((list.get(i)).getArticleBrand().getBrandId() == ID) {
				subList.add(list.get(i));
			}
		}
		return subList;
	}

	@Override
	@Transactional(readOnly = true)
	public Article getArticle(int ID) {
		Article article = (Article) sessionFactory.getCurrentSession()
				.createQuery("FROM Article A WHERE A.articleId = " + ID + "")
				.uniqueResult();
		return article;
	}

}